package com.jozen.modelbase.netwoek.util;

import android.graphics.Bitmap;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Base64Util {

    public static String byteToBase64(byte[] b){
        String image = Base64.encodeToString(b, Base64.DEFAULT);
        return image;
    }

    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] buff = new byte[in.available()];
            in.read(buff);
            base64 = Base64.encodeToString(buff,Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "data:file/bin;base64,"+base64;
    }


    public static String bitmapToBase64(Bitmap bitmap){
        String base64;

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
        byte[] bytes = out.toByteArray();
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        base64 = Base64.encodeToString(bytes,Base64.DEFAULT);
//        base64 = base64.replaceAll("\n","");
        base64 = Base64.encodeToString(bytes,Base64.NO_WRAP);//去掉换行符
        return "data:image/png;base64,"+ base64;
    }
}
